#include "CPlayerMgr.h"
#include "CLogin.h"


using namespace su;
using namespace std;
using namespace proto;

#define REG_MSG(cmd, fun) STATIC_RUN(MsgDispatch::Ins().RegMsgHandler(cmd, &CLogin::fun));

CLogin::CLogin(CPlayer& player)
	:EventCom(player.m_EventMgr)
	,m_owner(player)
{

}

void CLogin::LoginReq()
{
	auto f = [channelId = m_owner.ChannelId()]() {
		CPlayer* player = gPlayerMgr.Find(channelId);
		L_COND_V(player);
		LoginAccReq req;
		req.set_name(player->ChannelId());
		req.set_psw("1");
		player->Send(LOGIN_CMD, req);
		player->PDEBUG("connect login ok");
	};
	m_owner.m_Net.Connect(gSimClientSvr.Cfg().svrIp.c_str(), gSimClientSvr.Cfg().svrPort, f);
}


REG_MSG(LOGIN_CMD, LoginAccScFun)
void CLogin::LoginAccScFun(CPlayer& player, const LoginAccRes& res)
{
	// player.PDEBUG("rev LOGIN_CMD");
	L_COND_V(res.isok());
	auto f = [res, channelId = player.ChannelId()]() {
		CPlayer* player = gPlayerMgr.Find(channelId);
		L_COND_V(player);
		GetAccountInfoReq req;
		req.mutable_token()->CopyFrom(res.token());
		player->Send(GET_ACCOUNT_INFO_CMD, req);
		player->PDEBUG("connect access ok");
	};
	player.m_Net.Connect(res.acc_ip().c_str(), res.acc_port(), f);
}

REG_MSG(GET_ACCOUNT_INFO_CMD, GetAccountInfoResFun)
void CLogin::GetAccountInfoResFun(CPlayer &player, const GetAccountInfoRes &res)
{
	// player.PDEBUG("rev GET_ACCOUNT_INFO_CMD");
	if( res.actorls().size() == 0)
	{
		CreatePlayerReq req;
		req.set_name(player.Name());
		player.Send(CREATE_ACTOR_CMD, req);
		player.PDEBUG("req create new player");
		return;
	}

	LoginPlayerReq req;
	req.set_id(res.actorls(0).id());
	player.Send(LOGIN_ACTOR_CMD, req);
	player.PDEBUG("req login");
}

REG_MSG(CREATE_ACTOR_CMD, CreatePlayerResFun)
void CLogin::CreatePlayerResFun(CPlayer &player, const CreatePlayerRes &res)
{
	L_COND_V(res.isok());
	LoginPlayerReq req;
	req.set_id(res.id());
	player.Send(LOGIN_ACTOR_CMD, req);
	player.PDEBUG("create ok, req login");
}

REG_MSG(LOGIN_ACTOR_CMD, LoginPlayerResFun)
void CLogin::LoginPlayerResFun(CPlayer& player, const LoginPlayerRes& res)
{
	player.PDEBUG("========login ok=========");
	L_COND_V(player.Name() == res.actor().name());
	
}

